package com.platform.modules.job.task;

import com.alibaba.fastjson.JSON;
import com.platform.common.utils.Constant;
import com.platform.common.utils.JedisUtil;
import com.platform.modules.mall.entity.MallAccessRecordsGoodsEntity;
import com.platform.modules.mall.entity.MallAccessRecordsPageEntity;
import com.platform.modules.mall.service.MallAccessRecordsGoodsService;
import com.platform.modules.mall.service.MallAccessRecordsPageService;
import com.platform.modules.mall.service.MallGoodsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author Admin
 */
@Slf4j
@Component("accessRecordsTask")
public class AccessRecordsTask {

    @Autowired
    private MallAccessRecordsGoodsService mallAccessRecordsGoodsService;

    @Autowired
    private MallAccessRecordsPageService mallAccessRecordsPageService;

    @Autowired
    private MallGoodsService mallGoodsService;

    @Resource
    private JedisUtil jedisUtil;

    public void accessRecords(String date) {
        log.info("--------------------------开始访问记录插入任务--------------------------");
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, -1);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        if (date != null) {
            try {
                calendar.setTime(sdf.parse(date));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        String dateStr = sdf.format(calendar.getTime());


        //页面访问记录批量入库
        String pageJsonStr = jedisUtil.get(Constant.ACCESS_RECORDS_PAGE + dateStr);
        List<MallAccessRecordsPageEntity> pageEntityList = JSON.parseArray(pageJsonStr, MallAccessRecordsPageEntity.class);
        mallAccessRecordsPageService.saveBatch(pageEntityList);
        jedisUtil.del(Constant.ACCESS_RECORDS_PAGE + dateStr);

        //商品访问记录批量入库
        String goodsJsonStr = jedisUtil.get(Constant.ACCESS_RECORDS_GOODS + dateStr);
        List<MallAccessRecordsGoodsEntity> goodsEntityList = JSON.parseArray(goodsJsonStr, MallAccessRecordsGoodsEntity.class);
        //记录商品名称，防止重复查询数据库
        Map<String, String> goods = new HashMap<>();
        for (MallAccessRecordsGoodsEntity item : goodsEntityList) {
            if (goods.containsKey(item.getGoodsId())) {
                item.setGoodsName(goods.get(item.getGoodsId()));
            } else {
                item.setGoodsName(mallGoodsService.getById(item.getGoodsId()).getName());

                goods.put(item.getGoodsId(), item.getGoodsName());
            }
        }

        mallAccessRecordsGoodsService.saveBatch(goodsEntityList);
        jedisUtil.del(Constant.ACCESS_RECORDS_GOODS + dateStr);
        log.info("--------------------------结束访问记录插入任务--------------------------");
    }
}
